// 定义二叉树的节点类
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val) {
        this.val = val;
    }
}

public class Solution {

    public TreeNode invertTree(TreeNode root) {
        // 基本情况: 如果节点为空，则返回空
        if (root == null) {
            return null;
        }

        // 递归调用，先翻转左右子树
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);

        // 交换当前节点的左右子节点
        root.left = right;
        root.right = left;

        return root;
    }

    // 辅助函数来构造树并进行测试
    public static void main(String[] args) {
        // 示例1: root = [4,2,7,1,3,6,9]
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right = new TreeNode(7);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(9);

        Solution solution = new Solution();
        TreeNode invertedRoot = solution.invertTree(root);
        // 打印翻转后的二叉树
        printTree(invertedRoot);
    }

    // 辅助方法，用于打印树的节点值
    public static void printTree(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        printTree(root.left);
        printTree(root.right);
    }
}
